package com.windoent.yugioh.ui.activity.meinfo;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.AddressAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GoodsAddressListBean;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.dialog.DeleteSureDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/10 16:33
 * desc   :收货地址
 */
public class AddressActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private Button mBtnGetCode;
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private AddressAdapter adapter;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;

    @Override
    public int getLayout() {
        return R.layout.activity_goods_address;
    }

    @Override
    public void initView() {
        super.initView();

        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mBtnGetCode = (Button) findViewById(R.id.btn_get_code);
        mSmartLayout = (SmartRefreshLayout) findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    }

    @Override
    public void initData() {
        super.initData();
        initAdapter();
        initRefreshData();
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mBtnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //新增
                Intent intent = new Intent(AddressActivity.this, AddAddressActivty.class);
                intent.putExtra("add_address", true);
                startActivity(intent);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "收货地址界面");
        fresh();
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "收货地址界面");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
    }

    private void getAddressList(String page, String limit, boolean first) {
        showLoadingDialog("");
        PhoneLive.getAddressList(getUserToken(), page, limit, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(first);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GoodsAddressListBean json = gson.fromJson(response, GoodsAddressListBean.class);
                            if (json != null) {
                                GoodsAddressListBean.DataBean data = json.getData();
                                if (data != null) {
                                    List<GoodsAddressListBean.DataBean.ResBean> res = data.getRes();
                                    if (res != null) {
                                        if (first) {
                                            adapter.setNewInstance(res);
                                            mSmartLayout.finishRefresh(true);
                                        } else {
                                            adapter.addData(res);
                                            mSmartLayout.finishLoadMore(true);
                                        }

                                    } else freshFail(first);
                                } else freshFail(first);
                            } else freshFail(first);
                        } else freshFail(first);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        freshFail(first);
                    }
                } else {
                    freshFail(first);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddressAdapter();
        adapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.recycler_view_address_empty, mRecyclerView, false));
        adapter.setAnimationEnable(false);
        mRecyclerView.setAdapter(adapter);
        adapter.addChildClickViewIds(R.id.ll_modify, R.id.ll_delete);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                List<GoodsAddressListBean.DataBean.ResBean> data = adapter.getData();
                if (data != null) {
                    GoodsAddressListBean.DataBean.ResBean bean = data.get(position);
                    int id = view.getId();
                    if (id == R.id.ll_modify) {
                        //修改
                        Intent intent = new Intent(AddressActivity.this, AddAddressActivty.class);
                        intent.putExtra("add_address", false);
                        intent.putExtra("address_modify", bean);
                        startActivity(intent);
                    } else if (id == R.id.ll_delete) {
                        //刪除
                        showDeleleDialog(bean.getId() + "");
                    }
                }
            }
        });
    }

    private void showDeleleDialog(String goodsId) {
        DeleteSureDialog dialog = new DeleteSureDialog(AddressActivity.this);
        dialog.setTvContent(getString(R.string.string_sure_delete_address));
        dialog.setYesOnclickListener(new DeleteSureDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                deleteGoodsAddress(goodsId);
            }
        });
        dialog.show();
    }

    //删除地址
    private void deleteGoodsAddress(String id) {
        showLoadingDialog("");
        PhoneLive.deleteGoodsAddress(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            fresh();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initRefreshData() {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh();
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                loadMore();
            }
        });
    }

    private void loadMore() {
        mCount = mCount + 1;
        getAddressList(mCount + "", limit, false);
    }

    private void fresh() {
        mCount = 1;
        getAddressList(mCount + "", limit, true);
    }


    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }


}
